import { useAgentStore } from '@/stores/modules/agent';

// API配置文件 - 简洁统一模式
export const API_CONFIG = {
  // 工作流编排对话型应用API
  workflow: {
    baseURL: 'http://192.168.1.151:8109',
    apiKey: 'app-Ll4Gxkoph3yHWgNf3K0DwCyT',
    environment: 'develop',
    prefix: '/v1',
    endpoints: {
      // 应用内接口
      chatMessages: '/chat-messages',
      // 通用V1接口
      conversations: '/conversations',
      messages: '/messages',
      filesUpload: '/files/upload',
    }
  }
};

// 统一的API请求方法
export class ApiService {
  private config = API_CONFIG.workflow;

  // 获取完整URL
  private getUrl(endpoint: string): string {
    return `${this.config.baseURL}${this.config.prefix}${endpoint}`;
  }

  // 获取请求头
  private getHeaders(contentType?: string): HeadersInit {
    // 尝试获取当前智能体的 keyStr，如果没有则使用默认值
    let apiKey = this.config.apiKey;
    try {
      const agentStore = useAgentStore();
      const currentAgentKey = agentStore.getCurrentAgentKey();
      if (currentAgentKey) {
        apiKey = currentAgentKey;
      }
    } catch (error) {
      // 如果 store 还未初始化，使用默认值
      console.warn('Agent store not initialized, using default API key');
    }

    const headers: HeadersInit = {
      'Authorization': `Bearer ${apiKey}`,
    };
    if (contentType) {
      headers['Content-Type'] = contentType;
    }
    return headers;
  }

  // 通用GET请求
  async get(endpoint: string, params?: Record<string, any>) {
    const url = new URL(this.getUrl(endpoint));
    if (params) {
      Object.entries(params).forEach(([key, value]) => {
        if (value !== undefined && value !== null) {
          url.searchParams.set(key, String(value));
        }
      });
    }

    const response = await fetch(url.toString(), {
      method: 'GET',
      headers: this.getHeaders(),
    });

    if (!response.ok) {
      throw new Error(`GET请求失败: ${response.status}`);
    }

    return await response.json();
  }

  // 通用POST请求
  async post(endpoint: string, data?: any, contentType = 'application/json') {
    const body = contentType === 'application/json' ? JSON.stringify(data) : data;
    
    const response = await fetch(this.getUrl(endpoint), {
      method: 'POST',
      headers: this.getHeaders(contentType),
      body,
    });

    if (!response.ok) {
      throw new Error(`POST请求失败: ${response.status}`);
    }

    return await response.json();
  }

  // 流式POST请求
  async postStream(endpoint: string, data: any) {
    const response = await fetch(this.getUrl(endpoint), {
      method: 'POST',
      headers: this.getHeaders('application/json'),
      body: JSON.stringify(data),
    });

    if (!response.ok) {
      throw new Error(`流式请求失败: ${response.status}`);
    }

    return response;
  }
}

// 创建API服务实例
export const apiService = new ApiService();

// 兼容性导出（保持原有接口不变）
export const getWorkflowApiUrl = (endpoint: string) => `${API_CONFIG.workflow.baseURL}${API_CONFIG.workflow.prefix}${endpoint}`;
export const getWorkflowAppUrl = (endpoint: string) => `${API_CONFIG.workflow.baseURL}${API_CONFIG.workflow.prefix}${endpoint}`;
export const getWorkflowV1Url = (endpoint: string) => `${API_CONFIG.workflow.baseURL}${API_CONFIG.workflow.prefix}${endpoint}`;
export const getWorkflowConfig = () => API_CONFIG.workflow;
